from . import config, logger
import importlib

logger = logger.get_logger(__package__)


class InvalidMiddleware(Exception):
    pass


class PacketReject(Exception):
    pass


_middlewares = set()

middlewares = _middlewares

# 加载中间件
for mw in config.middlewares:
    module_path, cls_name = mw.rsplit(".", 1)
    module = importlib.import_module(module_path)
    MiddleWare = getattr(module, cls_name)
    middleware = MiddleWare()
    if not (hasattr(middleware, "pre_process") and callable(middleware.pre_process)):
        raise InvalidMiddleware("No 'pre_process' method found")

    if not (hasattr(middleware, "post_process") and callable(middleware.post_process)):
        raise InvalidMiddleware("No 'post_process' method found")

    logger.info("Loaded middleware ... ... [%s]" % mw)
    _middlewares.add(middleware)
